package org.mebusw.struts.davincicode;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * @author j1shen
 * @see DavinciCard
 */
public class CardHand extends ArrayList<DavinciCard>  implements Serializable{

	public CardHand() {

	}

	
	public void insertSort(DavinciCard card) {
		this.add(card);
	}

	/**
	 * @param card
	 *            the card to insert
	 * @param pos
	 *            the position to insert to
	 * @return true if the insertion is valid (but the card would not be
	 *         inserted)
	 */
	public boolean validatePos(DavinciCard card, int pos) {
		DavinciCard prev, succ;
		boolean result = false;

		try {
			prev = this.get(pos - 1);
			if (prev.isJoker()) { // skip one joker
				prev = this.get(pos - 2);
				if (prev.isJoker()) // skip another joker
					prev = this.get(pos - 3);
			}
			if (card.getValue() == prev.getValue() && (prev.isBlack())
					|| card.getValue() > prev.getValue())
				result = true;
		} catch (IndexOutOfBoundsException e) {
			// reach to the head (after skipping any jokers)
			result = true;
		}
	
		try {
			succ = this.get(pos + 1);
			if (succ.isJoker()) { // skip one joker
				succ = this.get(pos + 2);
				if (succ.isJoker()) // skip another joker
					succ = this.get(pos + 3);
			}
			if (card.getValue() == succ.getValue() && !(succ.isBlack())
					|| card.getValue() < succ.getValue())
				result &= true;
		} catch (IndexOutOfBoundsException e) {
			// reach to the tail (after skipping any jokers)
			result &= true;
		}
		
		return result;

	}
}
